﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Castle.Core.Logging;
using iTextSharp.text.pdf.qrcode;
using MediatR;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Traceability.Register.Application.Commonds.TraceabilityManagementCommonds;
using Traceability.Register.Domain;
using Traceability.Register.ErrorCode.Result;
using Traceability.Register.Infrastructrue;

using ZXing.Common;
using ZXing.Mobile;
using ZXing.QrCode;
using ZXing.Rendering;
using static Org.BouncyCastle.Math.Primes;

namespace Traceability.Register.Application.CommondHandlers.TraceabilityManagementCommondHandlers
{
    /// <summary>
    /// 导出溯源二维码请求命令处理
    /// </summary>
    public class GenerateQRCodeRequestCommondHandler : IRequestHandler<GenerateQRCodeRequestCommond, IActionResult>
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GenerateQRCodeRequestCommondHandler> logger;
        /// <summary>
        /// 溯源信息仓储
        /// </summary>
        private readonly IBaseRepository<Traceabilitys> baseRepository;
        private readonly IBaseRepository<Goods> repository;
        public GenerateQRCodeRequestCommondHandler(ILogger<GenerateQRCodeRequestCommondHandler> logger, IBaseRepository<Traceabilitys> baseRepository, IBaseRepository<Goods> repository)
        {
            this.logger = logger;
            this.baseRepository = baseRepository;
            this.repository = repository;
        }
        /// <summary>
        /// 导出溯源二维码请求命令处理
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public async Task<IActionResult> Handle(GenerateQRCodeRequestCommond request, CancellationToken cancellationToken)
        {
            try
            {
                var data = await baseRepository.GetAllAsync();
                var entity = await repository.GetAllAsync();
                var goodsInfo =   (from a in data
                                       join b in entity
                                       on a.GoodId equals b.GoodId
                                       where a.TraceabilityId == request.TraceabilityId
                                       select new
                                       {
                                           b.GoodName,
                                           a.ProductionBatch
                                       }).FirstOrDefault();

                if (goodsInfo == null)
                {
                    logger.LogError($"未找到对应的溯源信息，TraceabilityId: {request.TraceabilityId}");
                    return new NotFoundResult();
                }

                string qrCodeData = $"商品名称:{goodsInfo.GoodName},批次为:{goodsInfo.ProductionBatch},数量为:{request.BreedingSum}";
              

                // 将文本内容上传到 TextUploader，获取 URL
                using (var httpClient = new HttpClient())
                {
                    var content = new StringContent(qrCodeData, Encoding.UTF8, "text/plain");
                    var response = await httpClient.PostAsync("https://api.textuploader.com/v1/", content);
                    response.EnsureSuccessStatusCode();

                    var textUploaderUrl = await response.Content.ReadAsStringAsync();

                    // 将 TextUploader 的 URL 作为二维码数据
                    string apiUrl = $"https://api.qrserver.com/v1/create-qr-code/?size=300x300&data={Uri.EscapeDataString(textUploaderUrl)}";

                    // 生成二维码图片
                    var qrResponse = await httpClient.GetAsync(apiUrl);
                    var imageBytes = await qrResponse.Content.ReadAsByteArrayAsync();

                    return new FileContentResult(imageBytes, "image/png");
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"导出溯源二维码请求命令处理异常，TraceabilityId: {request.TraceabilityId}, 错误信息: {ex.Message}");
                return new BadRequestObjectResult("生成二维码失败，请稍后重试。");
            }
        }


    }
}
